<?php
set_include_path($_SERVER ['DOCUMENT_ROOT']);
include_once 'admin/includes/functions/admin-functions.php';
global $DBobject, $CONFIG, $SMARTY;

$error = "网页状态已经过期，请刷新页面";
$referer = parse_url($_SERVER['HTTP_REFERER']);
if ($referer['host'] == $GLOBALS['HTTP_HOST'] && checkToken('admin', $_POST["formToken"])) {
    $response = false;
    $url = false;
    
    switch ($_POST['action']) {
        case 'FilterClassesByTerm': //RETURN CLASSTERM-TREE-LIST TEMPLATE
            if (intval($_SESSION['user']['admin']['level']) > 1 && !empty($_SESSION['user']['admin']['franchisee'])) {
                $franchiseeIdArr = $_SESSION['user']['admin']['franchisee'];
            }
            $classTermObj = new ClassTermClass();
            $classterm_list = $classTermObj->GetClassesListByTermObjId($_POST['term_object_id'], $franchiseeIdArr);
            $SMARTY->assign('classterm_list', $classterm_list);
            $SMARTY->assign('token', $_POST["formToken"]);
            $template = $SMARTY->fetch('classterm-tree-list.tpl');
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    "template" => $template
            ));
            exit;
            
            
        case 'FilterClassesDropdownByTerm': //RETURN CLASSTERM-LIST-ATTENDANCE TEMPLATE
            if (intval($_SESSION['user']['admin']['level']) > 1 && !empty($_SESSION['user']['admin']['franchisee'])) {
                $franchiseeIdArr = $_SESSION['user']['admin']['franchisee'];
            }
            if (intval($_SESSION['user']['admin']['level']) == 3) {
                $instructorId = $_SESSION['user']['admin']['id'];
            }
            $classTermObj = new ClassTermClass();
            $classterm_list = $classTermObj->GetClassesListByTermObjId($_POST['term_object_id'], $franchiseeIdArr, $instructorId);
            $SMARTY->assign('term_name', $_POST['term_name']);
            $SMARTY->assign('sel_term_object_id', $_POST['term_object_id']);
            $SMARTY->assign('weeks', $_POST['weeks']);
            $SMARTY->assign('current_week', $_POST['current_week']);
            $SMARTY->assign('classterm_list', $classterm_list);
            $SMARTY->assign('token', $_POST["formToken"]);
            $template = $SMARTY->fetch('classterm-list-attendance.tpl');
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    "template" => $template
            ));
            exit;
            
            
        case 'GetAttendaceTable': //RETURN ATTENDANCE TABLE TEMPLATE (CLASSTERM-ENROLMENTS)
            $enrol_obj = new Enrolment();
            $enrolments = $enrol_obj->GetClassTermEnrolments($_POST['term_object_id'], $_POST['class_object_id'], $_POST['week'], '', false);
            $SMARTY->assign('term_object_id', $_POST['term_object_id']);
            $SMARTY->assign('class_object_id', $_POST['class_object_id']);
            $SMARTY->assign('week', $_POST['week']);
            $SMARTY->assign('enrolments', $enrolments);
            $SMARTY->assign('term_name', $_POST['term_name']);
            $SMARTY->assign('class_name', $_POST['class_name']);
            $SMARTY->assign('token', $_POST["formToken"]);
            $template = $SMARTY->fetch('table-attendance.tpl');
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    "template" => $template
            ));
            exit;
            
            
        case 'SaveAttendace':
            $enrol_obj = new Enrolment();
            foreach ($_POST['attendace'] as $id => $val) {
                $enrol_obj->SetEnrolmentAttendanceById($id, $val);
            }
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    "message" => 'Attendance roll saved.'
            ));
            exit;
            
            
        case 'WalkInForm':
            $error = '';
            $params = array(":walkin_admin_id"=>$_SESSION['user']['admin']['id'],
                                    ":walkin_term_object_id"=>$_POST['walkin_term_object_id'],
                                    ":walkin_class_object_id"=>$_POST['walkin_class_object_id'],
                                    ":walkin_week"=>$_POST['walkin_week'], ":walkin_user_gname"=>$_POST['walkin_user_gname'], ":walkin_user_surname"=>$_POST['walkin_user_surname'],
                                    ":walkin_student_name"=>$_POST['walkin_student_name'], ":walkin_student_surname"=>$_POST['walkin_student_surname'],
                                    ":walkin_email"=>$_POST['walkin_email'], ":walkin_phone"=>$_POST['walkin_phone'],
                                    ":walkin_notes"=>$_POST['walkin_notes']);
            $sql = "INSERT INTO tbl_walkin (walkin_admin_id, walkin_term_object_id, walkin_class_object_id, walkin_week, 
								walkin_user_gname, walkin_user_surname, walkin_student_name, walkin_student_surname, walkin_email, 
								walkin_phone, walkin_notes, walkin_created, walkin_modified 
							) values( :walkin_admin_id, :walkin_term_object_id, :walkin_class_object_id, :walkin_week, 
								:walkin_user_gname, :walkin_user_surname, :walkin_student_name, :walkin_student_surname, :walkin_email, 
								:walkin_phone, :walkin_notes, now(), now() )";
            $DBobject->wrappedSql($sql, $params);
            try {
                // SEND EMAIL
                $SMARTY->assign('data', $_POST);
                $SMARTY->assign('admin', $_SESSION['user']['admin']);
            
                $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                $domain = $protocol . $GLOBALS['HTTP_HOST'];
                $SMARTY->assign('DOMAIN', $domain);
                $COMP = json_encode($CONFIG->company);
                $SMARTY->assign('COMPANY', json_decode($COMP, true));
            
                $to = (string) $CONFIG->company->email_contact;
                $from = (string) $CONFIG->company->name;
                $fromEmail = 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']);
                $subject ='澳睿跑 (Ready Steady Go Kids) | Walk in form';
                $bcc = '';
                $body= $SMARTY->fetch('email-walkin-form.tpl');
                $success = sendMail($to, $from, $fromEmail, $subject, $body, $bcc, 0, $_SESSION['user']['admin']["id"]);
            } catch (Exception $e) {
                $error = 'Error: Email cannot be sent - ' .$e;
                $to = "readysteadygokids@gmail.com-dev,online@them.com.au";
                sendMail($to, $from, $fromEmail, 'Error: Walk in email cannot be sent - admin area(D)', "Message: {$e}");
                break;
            }
            echo json_encode(array(
                    "error" => $error,
                    "success" => $success
            ));
            exit;
            
            
        case 'AddWaitList':
            if (empty($_POST['user_id']) || empty($_POST['student_name']) || empty($_POST['student_dob'])) {
                $error = 'Error:  Make sure that the student details are completed (given name, surname and DOB).';
                break;
            }
            
            $error = '';
            
            $member_obj = new Member();
            $userArr = $member_obj->RetrieveById($_POST['user_id']);
            if (empty($_POST['student_id'])) {
                $studentArr = array('student_name'=>$_POST['student_name'],'student_surname'=>'','student_dob'=>$_POST['student_dob'],'student_medical'=>$_POST['student_medical']);
                $_POST['student_id'] = $member_obj->AddStudent($userArr['user_id'], $studentArr);
            }
            
            if (!empty($_POST['student_id']) && !empty($_POST['term_object_id']) && !empty($_POST['class_object_id'])) {
                $enrol_obj = new Enrolment();
                $response = $enrol_obj->AddStudentWaitList($_POST['student_id'], $_POST['term_object_id'], $_POST['class_object_id']);
            } else {
                $error = 'Error: Student cannot be created or the class was not selected.';
                break;
            }
            if ($response) {
                $sql = "SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_id = :id "; //Wait list
                if ($emailArr = $DBobject->wrappedSql($sql, array(':id' => 15))) {
                    $message = unclean($emailArr[0]['email_additional_content']);
                    $SMARTY->assign('message', 'Hi '.ucwords($userArr['user_gname']).'<br><br>'.$message);
                }
                try {
                    // SEND EMAIL
                    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                    $domain = $protocol . $GLOBALS['HTTP_HOST'];
                    $SMARTY->assign('DOMAIN', $domain);
                    $COMP = json_encode($CONFIG->company);
                    $SMARTY->assign('COMPANY', json_decode($COMP, true));
                        
                    $to = $userArr['user_email'];
                    $from = (string) $CONFIG->company->name;
                    $fromEmail = 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']);
                    $subject ='澳睿跑 (Ready Steady Go Kids) | Wait list class confirmation';
                    $bcc = '';
                    $SMARTY->assign('student', array('student_name'=>$_POST['student_name'],'student_surname'=>''));
                    
                    $classTermObj = new ClassTermClass();
                    $SMARTY->assign('classtermArr', $classTermObj->GetClassTermDataByObjIds($_POST['term_object_id'], $_POST['class_object_id']));
                    $body= $SMARTY->fetch('email-waitlist.tpl');
                    sendMail($to, $from, $fromEmail, $subject, $body, $bcc, $userArr['user_id'], $_SESSION['user']['admin']["id"]);
                } catch (Exception $e) {
                    $error = 'Error: Email cannot be sent - ' .$e;
                    $to = "readysteadygokids@gmail.com-dev,online@them.com.au";
                    sendMail($to, $from, $fromEmail, 'Error: Waitlist email cannot be sent - admin area(A)', "Message: {$e}");
                    break;
                }
                $success = "成功将学生添加到课程候选名单中。";
            } else {
                $error = "该学生已经在课程候选名单中。";
            }
            echo json_encode(array(
                    "error" => $error,
                    "success" => $success
            ));
            exit;
            
            
        case 'RemoveWaitList':
            if (empty($_POST['waitlist_id'])) {
                $error = '错误:  候选名单缺失。';
                break;
            }
            $error = '';
            $enrol_obj = new Enrolment();
            $response = $enrol_obj->RemoveStudentWaitList($_POST['waitlist_id']);
            if ($response) {
                $success = "This student was successfully removed from the class wait list.";
            } else {
                $error = "Unknown error: This student cannot be removed from the class wait list.";
            }
            echo json_encode(array(
                    "error" => $error,
                    "success" => $success
            ));
            exit;
            
            
        case 'getClasstermpanelTemplate': //RETURN CLASSTERM-PANEL TEMPLATE
            if (intval($_SESSION['user']['admin']['level']) > 1 && !empty($_SESSION['user']['admin']['franchisee'])) {
                $franchiseeIdArr = $_SESSION['user']['admin']['franchisee'];
            }
            $classTermObj = new ClassTermClass();
            foreach ($CONFIG->group as $gp) {
                foreach ($gp->section as $sp) {
                    if ((string) $sp->url == 'members') {
                        foreach ($sp->subsection as $sb) {
                            if ((string) $sb->url == 'new') {
                                $classTermObj->LoadClassesList($sb, $franchiseeIdArr, $_POST['term_object_id']);
                                break 3;
                            }
                        }
                    }
                }
            }
            $SMARTY->assign('selectClassOption', $_POST["selectClassOption"]);
            $SMARTY->assign('token', $_POST["formToken"]);
            $SMARTY->assign('type', $_POST["type"]);
            $template = $SMARTY->fetch('classterm-panel.tpl');
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    "template" => $template
            ));
            exit;
            
            
        case 'MoveEnrolment':
            $enrol_obj = new Enrolment();
            $newClassTerm = null;
            foreach ($_POST['classterm'] as $ct) {
                if (!empty($ct['id'])) {
                    $newClassTerm = $ct['id'];
                }
            }
            if (empty($newClassTerm)) {
                $error = "Please select the new class.";
                break;
            }
            
            $response = $enrol_obj->MoveEnrolment($_POST["student_id"], $_POST["old_term_object_id"], $_POST["old_class_object_id"], $newClassTerm);
            
            if ($response) {
                $member_obj = new Member();
                $studentArr = $member_obj->GetStudent($_POST['student_id']);
                $studentArr['enrolments'] = $enrol_obj->GetStudentEnrolments($_POST['student_id']);
                $SMARTY->assign('student', $studentArr);
                $template = $SMARTY->fetch('table-studentclass.tpl');
                try {
                    // SEND CONFIRMATION EMAIL
                    $userArr = $member_obj->RetrieveById($studentArr['student_user_id']);
                    $SMARTY->assign("user", $userArr);
                        
                    $sql = "SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_id = :id "; //Move enrolment
                    if ($emailArr = $DBobject->wrappedSql($sql, array(':id' => 4))) {
                        $message = unclean($emailArr[0]['email_additional_content']);
                        $SMARTY->assign('message', $message);
                    }
                    
                    $classTermObj = new ClassTermClass();
                    $classtermNewArr = $classTermObj->GetClassTermData($newClassTerm);
                    $SMARTY->assign('classtermNewArr', $classtermNewArr);
                    
                    $classtermArr = $classTermObj->GetClassDataByObjId($_POST["old_class_object_id"]);
                    $classtermArr = array_merge($classtermArr, $classTermObj->GetTermDataByObjId($_POST["old_term_object_id"]));
                    $SMARTY->assign('classtermArr', $classtermArr);
                        
                    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                    $domain = $protocol . $GLOBALS['HTTP_HOST'];
                    $SMARTY->assign('DOMAIN', $domain);
                    $COMP = json_encode($CONFIG->company);
                    $SMARTY->assign('COMPANY', json_decode($COMP, true));
                
                    $to = $userArr['user_email'];
                    $from = (string) $CONFIG->company->name;
                    $fromEmail = 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']);
                    $subject ='澳睿跑 (Ready Steady Go Kids) Move Enrolment';
                    $bcc = '';
                    $body= $SMARTY->fetch('email-move-enrol.tpl');
                    sendMail($to, $from, $fromEmail, $subject, $body, $bcc, $userArr['user_id'], $_SESSION['user']['admin']["id"]);
                } catch (Exception $e) {
                    $error = 'Error: Confirmation email cannot be sent - ' .$e;
                    $to = "readysteadygokids@gmail.com-dev,online@them.com.au";
                    sendMail($to, $from, $fromEmail, 'Error: Confirmation email cannot be sent - admin area(A)', "Message: {$e}");
                    break;
                }
            } else {
                $error = "Error! The class cannot be moved.";
                break;
            }
            
            echo json_encode(array(
                    "error" => null,
                    "success" => "The class was successfully moved.",
                    "response" => $response,
                    "studentID" => $_POST['student_id'],
                    "template" => $template
            ));
            exit;
        
            
        case 'MakeUpClass':
            $enrol_obj = new Enrolment();
            
            $newClassTermArr = array();
            $week = 0;
            foreach ($_POST['classterm'] as $id => $ct) {
                if (!empty($id) && !empty($ct['attr']['week'])) {
                    $newClassTermArr[] = $id;
                    $week = $ct['attr']['week'];
                }
            }
            if (empty($newClassTermArr)) {
                $error = "Please select one class.";
                break;
            } else {
                if (count($newClassTermArr)>1) {
                    $error = "Please select only one class.";
                    break;
                }
                $newClassTerm = $newClassTermArr[0];
            }
            
            $response = $enrol_obj->AddMakeUpEnrolment($_POST["student_id"], $_POST["old_term_object_id"], $_POST["old_class_object_id"], $newClassTerm, $week);
                
            if ($response) {
                $member_obj = new Member();
                $studentArr = $member_obj->GetStudent($_POST['student_id']);
                $studentArr['enrolments'] = $enrol_obj->GetStudentEnrolments($_POST['student_id']);
                $SMARTY->assign('student', $studentArr);
                $template = $SMARTY->fetch('table-studentclass.tpl');
                
                try {
                    // SEND CONFIRMATION EMAIL
                    $userArr = $member_obj->RetrieveById($studentArr['student_user_id']);
                    $SMARTY->assign("user", $userArr);
                    
                    $sql = "SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_id = :id "; //Make-up
                    if ($emailArr = $DBobject->wrappedSql($sql, array(':id' => 3))) {
                        $message = unclean($emailArr[0]['email_additional_content']);
                        $SMARTY->assign('message', $message);
                    }
                    
                    $classTermObj = new ClassTermClass();
                    $classtermArr = $classTermObj->GetClassTermData($newClassTerm);
                    $SMARTY->assign('classtermArr', $classtermArr);
                    $SMARTY->assign('session', getDateByWeekdayStartDate($classtermArr['class_weekday'], $classtermArr['term_start_date'], $week - 1, 'l, d M Y'));
                    
                    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                    $domain = $protocol . $GLOBALS['HTTP_HOST'];
                    $SMARTY->assign('DOMAIN', $domain);
                    $COMP = json_encode($CONFIG->company);
                    $SMARTY->assign('COMPANY', json_decode($COMP, true));
                
                    $to = $userArr['user_email'];
                    $from = (string) $CONFIG->company->name;
                    $fromEmail = 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']);
                    $subject ='澳睿跑 (Ready Steady Go Kids) Make-up Class';
                    $bcc = '';
                    $body= $SMARTY->fetch('email-makeup.tpl');
                    sendMail($to, $from, $fromEmail, $subject, $body, $bcc, $userArr['user_id'], $_SESSION['user']['admin']["id"]);
                } catch (Exception $e) {
                    $error = 'Error: Confirmation email cannot be sent - ' .$e;
                    $to = "readysteadygokids@gmail.com-dev,online@them.com.au";
                    sendMail($to, $from, $fromEmail, 'Error: Confirmation email cannot be sent - admin area(B)', "Message: {$e}");
                    break;
                }
            } else {
                $error = "Error! The make-up class cannot be created.";
                break;
            }
                
            echo json_encode(array(
                    "error" => null,
                    "success" => "The make-up class was successfully created.",
                    "response" => $response,
                    "studentID" => $_POST['student_id'],
                    "template" => $template
            ));
            exit;
                    
            
        case 'MoveTrialClass':
            $enrol_obj = new Enrolment();
                
            $newClassTermArr = array();
            $week = 0;
            foreach ($_POST['classterm'] as $id => $ct) {
                if (!empty($id) && !empty($ct['attr']['week'])) {
                    $newClassTermArr[] = $id;
                    $week = $ct['attr']['week'];
                }
            }
            if (empty($newClassTermArr)) {
                $error = "Please select one class.";
                break;
            } else {
                if (count($newClassTermArr)>1) {
                    $error = "Please select only one class.";
                    break;
                }
                $newClassTerm = $newClassTermArr[0];
            }
                
            $response = $enrol_obj->MoveTrialEnrolment($_POST["student_id"], $_POST["old_term_object_id"], $_POST["old_class_object_id"], $newClassTerm, $week);
            
            if ($response) {
                $member_obj = new Member();
                $studentArr = $member_obj->GetStudent($_POST['student_id']);
                $studentArr['enrolments'] = $enrol_obj->GetStudentEnrolments($_POST['student_id']);
                $SMARTY->assign('student', $studentArr);
                $template = $SMARTY->fetch('table-studentclass.tpl');
        
                try {
                    // SEND CONFIRMATION EMAIL
                    $userArr = $member_obj->RetrieveById($studentArr['student_user_id']);
                    $SMARTY->assign("user", $userArr);
                        
                    $sql = "SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_id = :id ";
                    if ($emailArr = $DBobject->wrappedSql($sql, array(':id' => 14))) {//Move-Trial
                        $message = unclean($emailArr[0]['email_additional_content']);
                        $SMARTY->assign('message', $message);
                    }
                    if ($emailArr = $DBobject->wrappedSql($sql, array(':id' => 1))) {//Trial
                        $message = unclean($emailArr[0]['email_additional_content']);
                        $SMARTY->assign('trialmessage', $message);
                    }
                        
                    $classTermObj = new ClassTermClass();
                    $classtermArr = $classTermObj->GetClassTermData($newClassTerm);
                    $SMARTY->assign('classtermArr', $classtermArr);
                    $SMARTY->assign('session', getDateByWeekdayStartDate($classtermArr['class_weekday'], $classtermArr['term_start_date'], $week - 1, 'l, d M Y'));
                        
                    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                    $domain = $protocol . $GLOBALS['HTTP_HOST'];
                    $SMARTY->assign('DOMAIN', $domain);
                    $COMP = json_encode($CONFIG->company);
                    $SMARTY->assign('COMPANY', json_decode($COMP, true));
        
                    $to = $userArr['user_email'];
                    $from = (string) $CONFIG->company->name;
                    $fromEmail = 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']);
                    $subject = '澳睿跑 (Ready Steady Go Kids) Move Trial';
                    $bcc = '';
                    $body= $SMARTY->fetch('email-move-trial.tpl');
                    sendMail($to, $from, $fromEmail, $subject, $body, $bcc, $userArr['user_id'], $_SESSION['user']['admin']["id"]);
                } catch (Exception $e) {
                    $error = 'Error: Confirmation email cannot be sent - ' .$e;
                    $to = "readysteadygokids@gmail.com-dev,online@them.com.au";
                    sendMail($to, $from, $fromEmail, 'Error: Confirmation email cannot be sent - admin area(C)', "Message: {$e}");
                    break;
                }
            } else {
                $error = "Error! The trial class cannot be moved.";
                break;
            }
        
            echo json_encode(array(
                    "error" => null,
                    "success" => "The trial class was successfully moved.",
                    "response" => $response,
                    "studentID" => $_POST['student_id'],
                    "template" => $template
            ));
            exit;
            
        case 'AddClassToCart':
            $enrol_obj = new Enrolment();
            $response = array();
            $_SESSION['enrol']['type'] = $_POST["enrolment"];
            if (!empty($_POST["enrolment"]) && $_POST["enrolment"] == 'T') {
                $response = $enrol_obj->AddToCart($_POST["product_id"], $_POST['trial']['attr'], $_POST["quantity"], 0, null, 0, $_POST["isClass"], $_POST["enrolment"], true);
            } else {
                $response = $enrol_obj->AddToCart($_POST["product_id"], $_POST['attr'], $_POST["quantity"], 0, null, 0, $_POST["isClass"], $_POST["enrolment"], true);
            }
                
            $totals = $enrol_obj->CalculateTotal($_SESSION['enrol']['students']);
            $productsOnCart = $enrol_obj->GetDataProductsOnCart();
            $SMARTY->assign('productsOnCart', $productsOnCart);
            $SMARTY->assign('totals', $totals);
            $SMARTY->assign('user', $_SESSION['enrol']['user']);
            $SMARTY->assign('classtermstudents', $_SESSION['enrol']['classtermStudent']);
            $SMARTY->assign('additional', $_SESSION['enrol']['additional']);
            $shoppingcart = $SMARTY->fetch('shopping-cart.tpl');
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    'response' => $response,
                    'shoppingcart' => $shoppingcart,
                    'charge'=> $totals['total']
            ));
            exit;
                
            
        case 'AddClassesToCart': // ======> NOT BEING USED!!!
            $enrol_obj = new Enrolment();
            $response = array();
            $_SESSION['enrol']['type'] = $_POST["enrolment"];
            foreach ($_POST['classterm'] as $ct) {
                if (!empty($ct['id'])) {
                    $response[] = $enrol_obj->AddToCart($ct['id'], $ct['attr'], $_POST["quantity"], 0, null, 0, $_POST["isClass"], $_POST["enrolment"], true);
                }
            }
            
            $totals = $enrol_obj->CalculateTotal($_SESSION['enrol']['students']);
            $productsOnCart = $enrol_obj->GetDataProductsOnCart();
            $SMARTY->assign('productsOnCart', $productsOnCart);
            $SMARTY->assign('totals', $totals);
            $SMARTY->assign('user', $_SESSION['enrol']['user']);
            $SMARTY->assign('classtermstudents', $_SESSION['enrol']['classtermStudent']);
            $SMARTY->assign('additional', $_SESSION['enrol']['additional']);
            $shoppingcart = $SMARTY->fetch('shopping-cart.tpl');
            $_SESSION['enrol']['step'] = 2;
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    'response' => $response,
                    'shoppingcart' => $shoppingcart
            ));
            exit;
            
            
        case 'DeleteItem':
            $enrol_obj = new Enrolment();
            $response = $enrol_obj->RemoveFromCart($_POST['cartitem_id']);
            $totals = $enrol_obj->CalculateTotal($_SESSION['enrol']['students']);
            $SMARTY->assign('additional', $_SESSION['enrol']['additional']);
            $itemNumber = $enrol_obj->NumberOfProductsOnCart();
            $totals['total'] += floatval($_SESSION['enrol']['additional']['amount']);
            $totals['discount'] = -1 * $totals['discount'];
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    'response' => $response,
                    'itemnumber' => $itemNumber,
                    'totals' => $totals,
                    'charge'=> $totals['total']
            ));
            exit;
                
            
        case 'addMember':
            $member_obj = new Member();
            $_SESSION['enrol']['user'] = $_POST['user'];
            
            if (empty($_POST['user']['user_id'])) {
                $newPass = genRandomString(10);
                $temp_str = getPass($_POST['user']['user_email'], $newPass);
                $newUserArr = array(
                        "username" => $_POST['user']['user_email'],
                        "email" => $_POST['user']['user_email'],
                        "gname" => $_POST['user']['user_gname'],
                        "surname" => $_POST['user']['user_surname'],
                        "password" => $newPass,
                        "user_warning" => $_POST['user']['user_warning'],
                        "user_hearabout" => $_POST['user']['user_hearabout'],
                        "wantpromo" => 1
                );
                
                $res = $member_obj->Create($newUserArr);
                if ($res['error'] || empty($res['id'])) {
                    $error = $res['error'];
                    break;
                }
                $update = 'created';
                try {
                    $sql = "SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_id = :id "; //New member
                    if ($emailArr = $DBobject->wrappedSql($sql, array(':id' => 9))) {
                        $message = unclean($emailArr[0]['email_additional_content']);
                        $SMARTY->assign('message', $message);
                    }
                    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                    $domain = $protocol . $GLOBALS['HTTP_HOST'];
                    $SMARTY->assign('DOMAIN', $domain);
                    $SMARTY->assign("name", $_POST['user']['user_gname']);
                    $SMARTY->assign("password", $newPass);
                    $COMP = json_encode($CONFIG->company);
                    $SMARTY->assign('COMPANY', json_decode($COMP, true));
                    $body= $SMARTY->fetch('email-newmember.tpl');
                    $to = $_POST['user']['user_email'];
                    
                    $from = (string) $CONFIG->company->name;
                    $fromEmail = "noreply@" . str_replace("www.", "", $GLOBALS['HTTP_HOST']);
                    $subject = '澳睿跑 (Ready Steady Go Kids) New Membership';
                    sendMail($to, $from, $fromEmail, $subject, $body, null, $res['id'], $_SESSION['user']['admin']["id"]);
                } catch (Exception $e) {
                    $to = "readysteadygokids@gmail.com-dev,online@them.com.au";
                    sendMail($to, $from, $fromEmail, 'Error: Create member - admin area(A)', "Message: {$e}");
                }
            } else {
                if (!empty($_POST['update_flag'])) {
                    $res2 = $member_obj->UpdateDetails($_POST['user']);
                    if ($res2['error']) {
                        $error = $res2['error'];
                        break;
                    } else {
                        $update = 'updated';
                    }
                }
                $res = array (
                        "id" => $_POST['user']['user_id'],
                        "gname" => $_POST['user']['user_gname'],
                        "surname" => $_POST['user']['user_surname'],
                        "email" => $_POST['user']['user_email']
                );
            }
            $_SESSION['user']['public'] = $res;
            $_POST['address']['B']['address_user_id'] = empty($_POST['user']['user_id'])? $res['id'] : $_POST['user']['user_id'];
            $_POST['address']['B']['address_name'] = $_POST['user']['user_gname'];
            $_POST['address']['B']['address_surname'] = $_POST['user']['user_surname'];
            $_SESSION['enrol']['address'] = $_POST['address'];
            $addressID = $member_obj->InsertNewAddress($_SESSION['enrol']['address']['B']);
            $_SESSION['address']['B'] = $member_obj->GetAddress($addressID);
            
            $member_obj->AddNotes($_SESSION['user']['admin']["id"], $_SESSION['user']['public']['id'], $_POST['user']['notes']);
            
            $enrol_obj = new Enrolment();
            $cartArr = $enrol_obj->GetDataCart();
            if (empty($cartArr['cart_user_id'])) {
                $enrol_obj->SetUserCart($_SESSION['user']['public']['id']);
            }
            $totals = $enrol_obj->CalculateTotal($_SESSION['enrol']['students']);
            $productsOnCart = $enrol_obj->GetDataProductsOnCart();
            $SMARTY->assign('productsOnCart', $productsOnCart);
            
            //Build template for existing students
            $studentArr = $member_obj->GetStudentsByUserId($_SESSION['user']['public']['id']);
            $SMARTY->assign('user', $_SESSION['enrol']['user']);
            $cnt = 0;
            $studentTemplate = '';
            $SMARTY->assign('selectedStudent', $_SESSION['enrol']['selectedStudent']);
            foreach ($studentArr as $student) {
                $SMARTY->assign('cnt', $cnt);
                $SMARTY->assign('student', $student);
                $SMARTY->assign('newmember', 1);
                $studentTemplate .= $SMARTY->fetch('student.tpl');
                $cnt++;
            }
            
            $SMARTY->assign('totals', $totals);
            $SMARTY->assign('classtermstudents', $_SESSION['enrol']['classtermStudent']);
            $SMARTY->assign('additional', $_SESSION['enrol']['additional']);
            $shoppingcart = $SMARTY->fetch('shopping-cart.tpl');
            $_SESSION['enrol']['step'] = 3;
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    'shoppingcart' => $shoppingcart,
                    'studentTemplate' => $studentTemplate,
                    'cnt' => $cnt,
                    'user'=> $update
            ));
            
            exit;
            
            
        case 'studentTemplate': //RETURN STUDENT TEMPLATE WITH CLASSES ON CART
            $enrol_obj = new Enrolment();
            $cartArr = $enrol_obj->GetDataCart();
            $productsOnCart = $enrol_obj->GetDataProductsOnCart();
            $userId = empty($cartArr['cart_user_id'])?$_SESSION['user']['public']['id']:$cartArr['cart_user_id'];
            $SMARTY->assign("user_id", $userId);
            $SMARTY->assign('productsOnCart', $productsOnCart);
            $SMARTY->assign('cnt', $_POST['cnt']);
            $SMARTY->assign('newmember', 1);
            $SMARTY->assign('trial_flag', $_POST['trial_flag']);
            $template = $SMARTY->fetch('student.tpl');
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    "template" => $template
            ));
            
            exit;
        
            
        case 'setStudent': //STORE STUDENT INFO IN SESSION - IT DOESN'T CREATE IT
            $studentArr = array();
            $classtermArr = array();
            $classtermStudentArr = array();
            $enrol_obj = new Enrolment();
            $productsOnCart = $enrol_obj->GetDataProductsOnCart();
            $error = null;
            $success = true;
            $hasEnrolmentArr = array();
            $missingDetails = "";
            
            $_SESSION['enrol']['step'] = 4;
            $isTrial = false;
            if ($_SESSION['enrol']['type'] == 'T') {
                $isTrial = true;
                $_SESSION['enrol']['step'] = 6;
            }
            
            $remove = array();
            foreach ($_POST['student'] as $key => $student) {
                if (!empty($student) && !empty($student['student_name']) && !empty($student['student_dob'])) {
                    $studentArr[] = $student;
                    if (!empty($student['cartitem_id'])) {
                        foreach ($student['cartitem_id'] as $ct => $val) {
                            /* ========> THE CLIENT WANTS THIS TO BE DISABLED <=============
							  if(!empty($student['student_id']) && $isTrial && $val) {
								$error = "This student '{$student['student_name']} {$student['student_surname']}' cannot have trial";
								$success = false;
								break 3;
							} */
                            if (empty($classtermArr["{$ct}"])) {
                                $classtermArr["{$ct}"] = $val;
                            } else {
                                $classtermArr["{$ct}"] = $classtermArr["{$ct}"] + $val;
                            }
                            if ($val) {
                                $classtermStudentArr["{$ct}"][] = $student['student_name'] . ' (' . dateDifference($student['student_dob'], date(), '%y') . ' years old)';

                                // Check current enrolments
                                if (!empty($student['student_id'])) {
                                    foreach ($productsOnCart as $item) {
                                        if ($item['cartitem_id'] == $ct && !$enrol_obj->ValidateStudentEnrolment($student['student_id'], $item['cartitem_product_id'])) {
                                            $hasEnrolment[] =  $student['student_name'] . ' 已经报名所选课程。';
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    if (!empty($student) && (empty($student['student_name']) || empty($student['student_dob']))) {
                        $missingDetails = '学生信息不完善，请填写姓名和生日。';
                    }
                    $remove[] = $key;
                }
            }
            
            
            if (!empty($hasEnrolment)) {
                $error = implode("<br>", $hasEnrolment);
                $success = false;
            } else {
                $classterm2 = array();
                //var_dump($productsOnCart);exit;
                foreach ($productsOnCart as $item) {
                    if (!empty($item['cartitem_class_flag'])) {
                        $qty = $classtermArr["{$item['cartitem_id']}"];
                        if (!empty($qty)) {
                            $classterm2["{$item['cartitem_id']}"] = $qty;
                        } else {
                            $_SESSION['enrol']['step'] = 3;
                            $error = empty($missingDetails)?"所选课程数量和学生数量不匹配":$missingDetails;
                            $success = false;
                        }
                    }
                }
            }
            if (!empty($classterm2)) {
                $enrol_obj->UpdateQtyCart($classterm2, true);
            }
            $_SESSION['enrol']['students'] = $studentArr;
            $_SESSION['enrol']['classtermStudent'] = $classtermStudentArr;
            
            $totals = $enrol_obj->CalculateTotal($_SESSION['enrol']['students']);
            //$productsOnCart = $enrol_obj->GetDataProductsOnCart();
            $SMARTY->assign('productsOnCart', $productsOnCart);
            $SMARTY->assign('totals', $totals);
            $SMARTY->assign('user', $_SESSION['enrol']['user']);
            $SMARTY->assign('classtermstudents', $_SESSION['enrol']['classtermStudent']);
            $SMARTY->assign('additional', $_SESSION['enrol']['additional']);
            $shoppingcart = $SMARTY->fetch('shopping-cart.tpl');
            
            echo json_encode(array(
                    "error" => $error,
                    "success" => $success,
                    'shoppingcart' => $shoppingcart,
                    'classtermStudentArr' => $classtermStudentArr,
                    'trial'=> $isTrial,
                    'remove'=>$remove,
                    'classtermArr'=>$classtermArr,
                    'classterm2'=>$classterm2
            ));
                
            exit;
            
            
        case 'AddProductToCart':
            $enrol_obj = new Enrolment();
            $response = $enrol_obj->AddToCart($_POST['product_id'], $_POST['attr'], $_POST["quantity"], $_POST['price'], null, null, null, null, true);

            $totals = $enrol_obj->CalculateTotal($_SESSION['enrol']['students']);
            $productsOnCart = $enrol_obj->GetDataProductsOnCart();
            $SMARTY->assign('productsOnCart', $productsOnCart);
            $SMARTY->assign('totals', $totals);
            $SMARTY->assign('user', $_SESSION['enrol']['user']);
            $SMARTY->assign('classtermstudents', $_SESSION['enrol']['classtermStudent']);
            $SMARTY->assign('additional', $_SESSION['enrol']['additional']);
            $shoppingcart = $SMARTY->fetch('shopping-cart.tpl');
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    'response' => $response,
                    'shoppingcart' => $shoppingcart,
                    'charge'=> $totals['total']
            ));
            exit;
            
            
        case 'ResetCart':
            $enrol_obj = new Enrolment();
            $_SESSION['user']['public'] = '';
            unset($_SESSION['user']['public']);
            $_SESSION['enrol'] = '';
            unset($_SESSION['enrol']);
            $enrol_obj->DeleteCart();
            session_regenerate_id();
            $enrol_obj->CreateCart();
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    "url" => $_POST['redirect']
            ));
            exit;

        case 'SetStep':
            $_SESSION['enrol']['step'] = $_POST['step'];
            $_SESSION['enrol']['type'] = empty($_SESSION['enrol']['type'])?'S':$_SESSION['enrol']['type'];
            echo json_encode(array(
                    "error" => null,
                    "success" => true
            ));
            exit;
            
            
        case 'SetCustomProduct':
            if (empty($_POST['customProduct']) || empty($_POST['paytype_id']) || ($_POST['paytype_id'] == '-2' && empty($_POST['debt_id']))) {
                $error = 'A mandatory field is empty';
                break;
            }
            $_SESSION['makepayment']['customProduct'] = $_POST['customProduct'];
            $_SESSION['makepayment']['paytype_id'] = $_POST['paytype_id'];
            $_SESSION['makepayment']['franchisee_id'] = $_POST['franchisee_id'];
            $_SESSION['makepayment']['debt_id'] = $_POST['debt_id'];
            $_SESSION['makepayment']['nextpayment'] = $_POST['nextpayment'];
            $_SESSION['makepayment']['step'] = 6;
            $enrol_obj = new Enrolment();
            
            $attributes = array("franchisee_id" => $_POST['franchisee_id']);
            if (!empty($_POST['debt_id']) && $_POST['paytype_id'] == '-2') {
                $attributes['debt_id'] = $_POST['debt_id'];
            }
            
            $response = $enrol_obj->AddCustomProductToCart($_POST['paytype_id'], $_POST['customProduct']['description'], $_POST['customProduct']['amount'], $attributes);
            
            $totals = $enrol_obj->CalculateTotal();
            $productsOnCart = $enrol_obj->GetDataProductsOnCart();
            $SMARTY->assign('productsOnCart', $productsOnCart);
            $SMARTY->assign('totals', $totals);
            $SMARTY->assign('user', $_SESSION['makepayment']['user']);
            $shoppingcart = $SMARTY->fetch('shopping-cart.tpl');
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    'response' => $response,
                    'charge'=> $totals['total'],
                    'shoppingcart' => $shoppingcart
            ));
            exit;
        
            
        case 'setAdditional':
            $_SESSION['enrol']['additional'] = $_POST['additional'];
            $_SESSION['enrol']['step'] = 6;
            $enrol_obj = new Enrolment();
            $totals = $enrol_obj->CalculateTotal($_SESSION['enrol']['students']);
            $productsOnCart = $enrol_obj->GetDataProductsOnCart();
            $SMARTY->assign('productsOnCart', $productsOnCart);
            $SMARTY->assign('totals', $totals);
            $SMARTY->assign('user', $_SESSION['enrol']['user']);
            $SMARTY->assign('classtermstudents', $_SESSION['enrol']['classtermStudent']);
            $SMARTY->assign('additional', $_SESSION['enrol']['additional']);
            $shoppingcart = $SMARTY->fetch('shopping-cart.tpl');
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    'response' => $response,
                    'charge'=> $totals['total'] + floatval($_SESSION['enrol']['additional']['amount']),
                    'shoppingcart' => $shoppingcart
            ));
            exit;
            
            
        case 'CancelEnrolment':
            $enrol_obj = new Enrolment();
            $error = null;
            $success = null;
            try {
                $response = $enrol_obj->UnpublishEnrolments($_POST['student_id'], $_POST['term_object_id'], $_POST['class_object_id'], $_POST['enrolment_type'], $_POST['enrolment_week']);
                if ($response) {
                    $success = 'Enrolment was successfully cancelled.';
                }
            } catch (Exception $e) {
                $error = $e;
            }
            
            echo json_encode(array(
                    "error" => $error,
                    "success" => $success,
                    'response' => $response
            ));
            exit;
            
            
        case 'ChangeOrderStatus':
            $pay_obj = new Bank(array());
            $pay_obj->SetOrderStatus($_POST['payment_id'], $_POST['status'], $_SESSION['user']['admin']["id"]);
            $published = 1;
            if ($_POST['status'] == 6 || $_POST['status'] == 9 || $_POST['status'] == 10) {
                $debtResponse = $pay_obj->UnsetDebtPaid($_POST['payment_id']);
                $published = 0;
            } else {
                $debtResponse = $pay_obj->ResetDebtPaid($_POST['payment_id']);
            }
            $enrol_obj = new Enrolment();
            $response = $enrol_obj->setEnrolmentPublishByPaymentId($_POST['payment_id'], $published);
            
            echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    "debtResponse" => $debtResponse,
                    'response' => $response
            ));
            exit;
            
            
        case 'PlaceOrder':
            $enrol_obj = new Enrolment();
            $order_cartId = $enrol_obj->cart_id;
            $orderData = $enrol_obj->GetDataCart($order_cartId);
            $itemNumber = $enrol_obj->NumberOfProductsOnCart($order_cartId);
            
            // CREATE STUDENTS AND ENROL STUDENTS
            $orderItems = $enrol_obj->GetDataProductsOnCart($order_cartId);
            $students_cnt = 0;
            $classes_cnt=0;
            $pr_classes_ck = array();
            $create = 0;
            if (!empty($_SESSION['enrol']['students'])) {
                $member_obj = new Member();
                foreach ($_SESSION['enrol']['students'] as $student) {
                    if (empty($student['student_id'])) {
                        $create++;
                    }
                    foreach ($orderItems as $item) {
                        if ($item['cartitem_class_flag'] == 1 && empty($pr_classes_ck["{$item['cartitem_id']}"])) {
                            $pr_classes_ck["{$item['cartitem_id']}"]=1;
                            $classes_cnt=$classes_cnt+intval($item['cartitem_quantity']);
                        }
                        if (!empty($student['cartitem_id'][$item['cartitem_id']])) {
                            $students_cnt++;
                            foreach ($item['attributes'] as $attr) {
                                if ($attr['cartitem_attr_attribute_name'] == 'week') {
                                }
                            }
                        }
                    }
                }
            }
            if ($students_cnt != $classes_cnt) {
                $_SESSION['enrol']['step'] = 3;
                $postvars = $_POST;
                $postvars['cc']['number'] = '';
                $to = "readysteadygokids@gmail.com-dev,online@them.com.au";
                sendMail($to, (string) $CONFIG->company->name, 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']), '(A)No Students!!', "Order: ".$order_cartId.'-'.date("is")."</br> Session: ".print_r($_SESSION, true)." </br> Post: ".print_r($postvars, true)." </br> CART: ".print_r($orderItems, true)."</br>student cnts: {$students_cnt}</br>class cnts: {$classes_cnt}");
                $_SESSION['error'] = "Something went wrong. The selected students and classes do not match. Please select the number of students equal to the classes you have.";
                echo json_encode(array(
                  "error" => "Something went wrong. The selected students and classes do not match. Please refresh the page",
                  "success" => false,
                  "javascript"=>"$('#accordion').find('.collapse.in').removeClass('in');$('.step3').collapse('show');$('#student-form').find('.error-alert').find('strong').html('There was an error linking the student to the selected class. Please select a student and click next.');$('#student-form').find('.error-alert').fadeIn('slow');$('#step6-btn').show();$('#processing-div').hide();$('#payment-form').find('.error-alert').hide();"
                ));
                die();
            }
            //THIS IS TRYING TO TRACE ERROR;
                
            if (!empty($_SESSION['user']['public']) && !empty($_SESSION['address']['B']) && !empty($itemNumber) && !empty($orderData['cart_user_id']) && ($_SESSION['user']['public']['id'] == $orderData['cart_user_id'])) {
                $userArr = $_SESSION['user']['public'];
                $addressID = $_SESSION['address']['B']['address_id'];
                
                $orderNumber = $order_cartId.'-'.date("is");
            
                $shippingFee = 0;
            
                $totals = $enrol_obj->CalculateTotal($_SESSION['enrol']['students']);
                $additional = empty($_SESSION['enrol']['additional']['amount'])? 0 : floatval($_SESSION['enrol']['additional']['amount']);
                $total = $totals['total'] + $shippingFee + $additional;
                $chargedAmount = (empty($_POST['cc']['amount']))? 0 : $_POST['cc']['amount'];
                $surchargePer = floatval($CONFIG->payment_gateway->surcharge_percentage) / 100;

                $surcharge = ($_POST['payment-method'] == 'cc' && ($chargedAmount > 0)  && ($chargedAmount > 0))? round($chargedAmount * $surchargePer, 2) : 0;
                $chargedAmount = round($chargedAmount + $surcharge, 2);
                $total = round($total + $surcharge, 2);
                $gst = round(($totals['GST_Taxable'] + $shippingFee) * 100 / ($TAX_RATE + 100), 2);
        
                //CHECK PARTIAL PAYMENT SET CORRECTLY
                if (empty($_POST['nextpayment']) && $chargedAmount != $total) {
                    $postvars = $_POST;
                    $postvars['cc']['number'] = '';
                    $to = "readysteadygokids@gmail.com-dev,online@them.com.au,readysteadygokids@gmail.com-dev";
                    sendMail($to, (string) $CONFIG->company->name, 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']), '(A)Invalid Partial Payment [Empty Next Paymenet Date]!!', "Order: ".$order_cartId.'-'.date("is")."</br> Session: ".print_r($_SESSION, true)." </br> Post: ".print_r($postvars, true)." </br> CART: ".print_r($orderItems, true)."</br>student cnts: {$students_cnt}</br>class cnts: {$classes_cnt}");
                    $_SESSION['error'] = "It looks like you are trying to make a partial payment without setting the next payment date. Please check that the payment information is set correctly.";
                    echo json_encode(array(
                      "error" => "It looks like you are trying to make a partial payment without setting the next payment date. Please check that the payment information is set correctly.",
                      "success" => false,
                        "chargedAmount" => $chargedAmount,
                        "total" => $total,
                    "javascript"=>"$('#step6-btn').show();$('#processing-div').hide();"
                    ));
                    die();
                }
                //END
                
                $params = array(
                        'payment_billing_address_id' => $addressID,
                        'payment_shipping_address_id' => $addressID,
                        'payment_transaction_no' => $orderNumber,
                        'payment_cart_id' => $order_cartId,
                        'payment_user_id' => $userArr['id'],
                        'payment_subtotal' => $totals['subtotal'],
                        'payment_discount' => $totals['discount'],
                        'payment_shipping_fee' => $shippingFee,
                        'payment_shipping_method' => '',
                        'payment_shipping_comments' =>  '',
                    'payment_status' => 'P',
                        'payment_additional_description' =>  $_SESSION['enrol']['additional']['description'],
                        'payment_additional' =>  $additional,
                        'payment_surcharge' =>  $surcharge,
                        'payment_payee_name' => $_POST['cc']['name'],
                        'payment_charged_amount' => $chargedAmount,
                        'payment_total' => $total,
                        'payment_gst' => $gst,
                    'payment_method' => '',
                        'next_payment_date' => $_POST['nextpayment'],
                        'isMakePayment' => (empty($_SESSION['makepayment'])?false:true)
                );
                
                $pay_obj = new PaymentCommBank($params);
                $response = false;
                
                try {
                    $CCdata =  array('amount'=>$chargedAmount);
                    if (!empty($_POST['cc'])) {
                        $CCdata = array_merge($_POST['cc'], $CCdata);
                    }
                    $pay_obj->PreparePayment($CCdata);
                        
                    $subject ='澳睿跑 (Ready Steady Go Kids) | 订单确认';
                    
                    // ORDER STATUS
                    $status = 1; // Approved - No payment
                        
                    //CREDIT CARD PAYMENT
                    if ($_POST['payment-method'] == 'cc' && !empty($chargedAmount) && ($total > 0)) {
                        $status = 3; // Approved - Credit Card - Partial
                        if ($chargedAmount == $total) {
                            $status = 2; // Approved - Credit Card - Full
                        }
                        $response = $pay_obj->Submit();
                        $paymentId = $pay_obj->GetPaymentId();
                        $subject ='澳睿跑 (Ready Steady Go Kids) Payment Received';
                            
                        // BANK TRANSFER - NOT CREDIT CARD
                    } elseif ($_POST['payment-method'] == 'bt' && ($total > 0)) {
                        $status = 8; // Pending - Bank Transfer - Partial
                        if ($chargedAmount == $total) {
                            $status = 7; // Pending - Bank Transfer - Full
                        }
                        $bankTransfer = 1;
                        $params['payment_method'] = 'Bank Transfer';
                        if ($paymentId = $pay_obj->StorePaymentRecord($params)) {
                            $response = true;
                        }
                            
                        // TRIAL ONLY WHEN CHARGED-AMOUNT IS ZERO (0)
                    } else {
                        $params['payment_status'] = 'A';
                        $params['payment_method'] = 'No payment required';
                        if ($paymentId = $pay_obj->StorePaymentRecord($params)) {
                            $response = true;
                        }
                    }
                } catch (Exception $e) {
                    $error = 'Payment Error: ' .$e;
                    break;
                }

                if ($response) {
                    // PAYMENT SUCCESS
                    $enrol_obj->CloseCart();

                    // SET ORDER STATUS
                    $pay_obj->SetOrderStatus($paymentId, $status, $_SESSION['user']['admin']["id"]);

                    $order = $enrol_obj->GetDataCart($order_cartId);
                    $payment = $pay_obj->GetPaymentRecord($paymentId);
                    $orderItems = $enrol_obj->GetDataProductsOnCart($order_cartId);
                    
                    // CREATE STUDENTS AND ENROL STUDENTS
                    try {
                        $students_cnt_secnd = 0;
                        $classes_cnt_secnd=0;
                        $pr_classes = array();
                        $create = 0;
                        $new_student = false;
                        if (!empty($_SESSION['enrol']['students'])) {
                            $member_obj = new Member();
                            foreach ($_SESSION['enrol']['students'] as $student) {
                                if (empty($student['student_id'])) {
                                    $student['student_id'] = $member_obj->addStudent($userArr['id'], $student);
                                }
                                foreach ($orderItems as $item) {
                                    if ($item['cartitem_class_flag'] == 1 && empty($pr_classes["{$item['cartitem_id']}"])) {
                                        $pr_classes["{$item['cartitem_id']}"] = 1;
                                        $classes_cnt_secnd= $classes_cnt_secnd + intval($item['cartitem_quantity']);
                                    }
                                    if (!empty($student['cartitem_id'][$item['cartitem_id']])) {
                                        $students_cnt_secnd++;
                                        foreach ($item['attributes'] as $attr) {
                                            if ($attr['cartitem_attr_attribute_name'] == 'week') {
                                                $enrol_obj->addEnrolmentByClasstermId($student['student_id'], $item['cartitem_product_id'], $attr['cartitem_attr_attr_value_name'], $item['cartitem_enrolment_type'], 1, $paymentId);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if ($students_cnt_secnd != $classes_cnt_secnd) {
                            $to = "liu.chang@chinaott.net";
                            sendMail($to, $from, $fromEmail, '(A)No Students!!', "Order: ".$order_cartId.'-'.date("is")."</br> Session: ".print_r($_SESSION, true)." </br> Post: ".print_r($_POST, true)."</br>student cnts: {$students_cnt}</br>class cnts: {$classes_cnt}</br>second student cnts: {$students_cnt_secnd}</br>second class cnts: {$classes_cnt_secnd}");
                        }
                        
                        if (!empty($_SESSION['makepayment'])) {
                            foreach ($orderItems as $item) {
                                // PARTIAL PAYMENT VIA MAKE-A-PAYMENT
                                if ($item['cartitem_product_id'] == -2) {
                                    foreach ($item['attributes'] as $attr) {
                                        if ($attr['cartitem_attr_attribute_name'] == 'debt_id') {
                                            $debtArr = $pay_obj->GetDebt($attr['cartitem_attr_attr_value_name']);
                                            $newDebt = round($debtArr['debt_amount'] - $chargedAmount + $surcharge, 2);
                                            $pay_obj->SetDebtPaidDate($attr['cartitem_attr_attr_value_name'], $paymentId);
                                            if ($newDebt > 0) {
                                                $pay_obj->SetNextPaymentDate($debtArr['debt_payment_id'], $newDebt, $_SESSION['makepayment']['nextpayment']);
                                            } else {
                                                //Change order status from partial to full
                                                $originalOrderStatus = $pay_obj->GetOrderStatus($debtArr['debt_payment_id']);
                                                if ($originalOrderStatus == 3) {//Credit card
                                                    $pay_obj->SetOrderStatus($debtArr['debt_payment_id'], 2, $_SESSION['user']['admin']["id"]);
                                                } elseif ($originalOrderStatus == 5 || $originalOrderStatus == 7 || $originalOrderStatus == 8) {
                                                    // 7:	Pending - Bank transfer - Full
                                                    // 8:	Pending - Bank transfer - Partial
                                                    $pay_obj->SetOrderStatus($debtArr['debt_payment_id'], 4, $_SESSION['user']['admin']["id"]);
                                                }
                                            }
                                        }
                                    }
                                    //UPDATE BANK TRANSFER PAYMENT STATUS: Pending => Approved
                                    if ($status == 7) {
                                        $status = 4;
                                        $pay_obj->SetPaymentStatus($paymentId, 'A');
                                        $pay_obj->SetOrderStatus($paymentId, $status, $_SESSION['user']['admin']["id"]);
                                    }
                                }
                            }
                            $_SESSION['makepayment'] = '';
                            unset($_SESSION['makepayment']);
                            $SMARTY->assign('buttonTitle', 'Make another payment');
                        }
                    } catch (Exception $e) {
                        $to = "readysteadygokids@gmail.com-dev,online@them.com.au,readysteadygokids@gmail.com-dev";
                        sendMail($to, (string) $CONFIG->company->name, 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']), 'Back-end (A)ERROR adding Students!!', "Order: ".$order_cartId.'-'.date("is")."</br> Session: ".print_r($_SESSION, true)." </br> Post: ".print_r($_POST, true)." </br> CART: ".print_r($orderItems, true)."</br>student cnts: {$students_cnt}</br>class cnts: {$classes_cnt}");
                    }
                    
                    try {
                        // SEND CONFIRMATION EMAIL
                        $SMARTY->assign("user", $userArr);
                        $SMARTY->assign('shipping', $_SESSION['address']['B']);
                        $SMARTY->assign('order', $order);
                        $SMARTY->assign('payment', $payment);
                        $SMARTY->assign('orderItems', $orderItems);
                        $SMARTY->assign('bankTransfer', $bankTransfer);
                        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                        $domain = $protocol . $GLOBALS['HTTP_HOST'];
                        $SMARTY->assign('DOMAIN', $domain);
                        $SMARTY->assign('status', $status);
                        $SMARTY->assign('nextpayment', $_POST['nextpayment']);
            
                        // ================= Custom Messages ================
                        $sql = "SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_id = :id ";
                        if ($res = $DBobject->wrappedSql($sql, array(':id' => 1))) {//Trial
                            $message = unclean($res[0]['email_additional_content']);
                            $SMARTY->assign('message', $message);
                        }
                        if ($res = $DBobject->wrappedSql($sql, array(':id' => 11))) {//CreditCard
                            $message = unclean($res[0]['email_additional_content']);
                            $SMARTY->assign('creditMessage', $message);
                        }
                        if ($res = $DBobject->wrappedSql($sql, array(':id' => 12))) {//Bank
                            $message = unclean($res[0]['email_additional_content']);
                            $SMARTY->assign('bankMessage', $message);
                        }
                        // ==================================================
                        
                        $COMP = json_encode($CONFIG->company);
                        $SMARTY->assign('COMPANY', json_decode($COMP, true));
                        
                        $to = $userArr['email'];
                        //$bcc = (string) $CONFIG->company->email_orders;
                        
                        $from = (string) $CONFIG->company->name;
                        $fromEmail = 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']);
                        $body= $SMARTY->fetch('email-confirmation.tpl');
                        if ($mailID = sendMail($to, $from, $fromEmail, $subject, $body, $bcc, $userArr['id'], $_SESSION['user']['admin']["id"])) {
                            $pay_obj->SetInvoiceEmail($paymentId, $mailID);
                        }
                    } catch (Exception $e) {
                        $error = 'Error: Confirmation email cannot be sent - ' .$e;
                        $to = "readysteadygokids@gmail.com-dev,online@them.com.au";
                        sendMail($to, $from, $fromEmail, 'Error: Confirmation email cannot be sent - admin area(D)', "Message: {$e}");
                        break;
                    }
                    
                    //CREATE GOOGLE ANALYTIC ENHANCED ECOMMERCE EVENT
                    try {
                        $ga_id = (string) $CONFIG->google_analytics->id;
                        if (!empty($ga_id)) {
                            $totals = array('id'=>$orderNumber,'total'=>$total,'tax'=>$gst,'shipping'=>$shippingFee,'coupon'=>'');
                            $cartitemGA = $enrol_obj->getCartitemsInfoEnEc_GA($order_cartId);
                            if (!empty($_SESSION['enrol']['additional']['description']) || !empty($additional)) {
                                $cnt = count($cartitemGA) + 1;
                                $cartitemGA[$cnt]['id'] = 'additional';
                                $cartitemGA[$cnt]['name'] = $_SESSION['enrol']['additional']['description'];
                                $cartitemGA[$cnt]['category'] = '';
                                $cartitemGA[$cnt]['brand'] = '';
                                $cartitemGA[$cnt]['variant'] = '';
                                $cartitemGA[$cnt]['price'] = $additional;
                                $cartitemGA[$cnt]['$quantity'] = 1;
                            }
                            //sendGAEnEcPurchase($ga_id, $totals, $cartitemGA);
                            sendGAEcPurchase($ga_id, $totals, $cartitemGA);
                            sendGAEvent($ga_id, 'Checkout', 'Payment', $_SERVER['HTTP_REFERER']);
                        }
                        
                        //OLD GA ID
                        $ga_id = (string) $CONFIG->google_analytics->old_id;
                        if (!empty($ga_id)) {
                            $totals = array('id'=>$orderNumber,'total'=>$total,'tax'=>$gst,'shipping'=>$shippingFee,'coupon'=>'');
                            $cartitemGA = $enrol_obj->getCartitemsInfoEnEc_GA($order_cartId);
                            if (!empty($_SESSION['enrol']['additional']['description']) || !empty($additional)) {
                                $cnt = count($cartitemGA) + 1;
                                $cartitemGA[$cnt]['id'] = 'additional';
                                $cartitemGA[$cnt]['name'] = $_SESSION['enrol']['additional']['description'];
                                $cartitemGA[$cnt]['category'] = '';
                                $cartitemGA[$cnt]['brand'] = '';
                                $cartitemGA[$cnt]['variant'] = '';
                                $cartitemGA[$cnt]['price'] = $additional;
                                $cartitemGA[$cnt]['$quantity'] = 1;
                            }
                            //sendGAEnEcPurchase($ga_id, $totals, $cartitemGA);
                            sendGAEcPurchase($ga_id, $totals, $cartitemGA);
                            sendGAEvent($ga_id, 'Checkout', 'Payment', $_SERVER['HTTP_REFERER']);
                        }
                    } catch (Exception $e) {
                        $to = "readysteadygokids@gmail.com-dev,online@them.com.au";
                        sendMail($to, $from, $fromEmail, 'ERROR: GA ecommerce - admin area', "Order: {$orderNumber}</br>Message: {$e}");
                    }
                        
                     
                    //SET USED DISCOUNT CODE
                    try {
                        if ($order['cart_discount_code']) {
                            $enrol_obj->SetUsedDiscountCode($order['cart_discount_code']);
                            $discountData = $enrol_obj->GetDiscountData($order['cart_discount_code']);
                            /* if($discountData['discount_unlimited_use'] == '0'){
								try{
										// SEND NOTIFICATION EMAIL
									$SMARTY->assign('user',$_SESSION['user']['public']);
									$SMARTY->assign('discount',$discountData);
				    		  $buffer= $SMARTY->fetch('email-discount.tpl');
							    $to = "readysteadygokids@gmail.com-dev";
							    $bcc = "Ready Steady Go Kids";
							    $from = str_replace ( "www.", "", $GLOBALS['HTTP_HOST'] );
							    $fromEmail = 'noreply@' . str_replace ( "www.", "", $GLOBALS['HTTP_HOST'] );
							    $subject = 'A discount code has been used.';
							    $body = $buffer;
							    $mailID = sendMail($to, $from, $fromEmail, $subject, $body, $bcc);
								}catch(Exception $e){}
							} */
                        }
                    } catch (Exception $e) {
                    }
                  
                  // OPEN NEW CART
                    session_regenerate_id();
                    $enrol_obj->CreateCart();
                  
                  // CLEAR DATA
                    $_SESSION['user']['public'] = '';
                    unset($_SESSION['user']['public']);
                    $_SESSION['enrol'] = '';
                    unset($_SESSION['enrol']);
                    
                    
                    if (preg_match('/buy-merchandise/', $_SERVER['HTTP_REFERER'])) {
                        $SMARTY->assign('buttonTitle', '继续订购其他课程');
                    }
                
                    // REDIRECT TO THANK YOU PAGE
                    $ConfirmationMessage = ($_SESSION['enrol']['type'] == 'T')? "体验课程成功添加。" : "订单确认。";
                    $SMARTY->assign('message', $ConfirmationMessage);
                    $template= $SMARTY->fetch('checkout-completed.tpl');
                    echo json_encode(array(
                            "error" => null,
                            "success" => true,
                            "template" => $template
                    ));
                    exit;
                } else {
                    $error = $pay_obj->GetErrorMessage();
                    $error = !empty($error)? $error : '付款错误，请检查所填信息并重试。';
                }
            } else {
                $error = '支付失败: Missing fields. Please refresh the page.';
                if (empty($_SESSION['user']['public'])) {
                    $error .= "</br> 此付款没有设置用户成员。";
                }
                if (!empty($_SESSION['address']['B'])) {
                    $error .= "</br> 我们似乎没有这个用户的送货地址。";
                }
                if (!empty($itemNumber)) {
                    $error .= "</br> 似乎没有任何产品需要支付。";
                }
                if (!empty($orderData['cart_user_id'])) {
                    $error .= "</br> 此购物车与用户不关联。";
                }
                if (!($_SESSION['user']['public']['id'] == $orderData['cart_user_id'])) {
                    $error .= "</br> 公共成员与此购物车不匹配。";
                }
                $error .= "</br> <a href='{$_SERVER['HTTP_REFERER']}'>请刷新页面.</a>";
            }
            
            echo json_encode(array(
                    "error" => $error,
                    "success" => false
            ));
            exit;
    }
}
echo json_encode(array("error"=>$error));
die();
